package com.gopay.bis.service.bank.impl;

import com.gopay.bis.common.util.BisPayCheckUtils;
import com.gopay.bis.manager.bank.BankOrderManager;
import com.gopay.bis.manager.bank.external.BisPayMessageManager;
import com.gopay.bis.manager.bank.payconfig.BisBankExtConfigManager;
import com.gopay.bis.manager.bank.payconfig.BisBankProductLimitMerchantsManager;
import com.gopay.bis.manager.bank.payconfig.BisBankSpecialMerchantsManager;
import com.gopay.bis.service.bank.BankOrderService;
import com.gopay.bis.service.bank.external.BisExternalPlatformService;
import com.gopay.bis.service.bank.query.BisBankWhiteListMerchantsService;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.*;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.cps.manager.order.CpsGeneralMainOrderQueryManager;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.abc.ebank.AbcB2bMessage;
import com.gopay.common.domain.bank.abc.ebank.AbcB2cMessage;
import com.gopay.common.domain.bank.bobj.ebank.BobjB2cMessage;
import com.gopay.common.domain.bank.bocom.ebank.pay.b2b.req.BocomB2bReq;
import com.gopay.common.domain.bank.citic.ebank.pay.CiticB2bMessage;
import com.gopay.common.domain.bank.citic.ebank.pay.CiticB2cMessage;
import com.gopay.common.domain.bank.cmbc.ebank.CmbcB2bMessage;
import com.gopay.common.domain.bank.cmbc.ebank.CmbcB2cMessage;
import com.gopay.common.domain.bank.external.BisBankMerchant;
import com.gopay.common.domain.bank.external.BisPayMessage;
import com.gopay.common.domain.bank.hxbc.ebank.pay.req.HXEB2CReqPay;
import com.gopay.common.domain.bank.icbc.ebank.pay.IcbcB2cMessage;
import com.gopay.common.domain.bank.yspay.ebank.YspayMessage;
import com.gopay.common.domain.bis.BaseBisBankExtConfig;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.exception.GopayException;
import com.gopay.common.order.bankorder.trade.InitialSpringBeanName;
import com.gopay.common.order.bankorder.trade.TradeType;
import com.gopay.common.util.spring.SpringContextUtil;
import com.gopay.remote.bank.BankInteractRemoteService;
import com.gopay.remote.bank.WapPayInteractRemoteService;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 閾惰鎿嶄綔Service瀹炵幇
 * @WapInteractServiceImpl.java
 * @author weiyajun
 */
@Service("wapPayService")
public class WapPayServiceImpl implements WapPayInteractRemoteService {

	private static Logger logger = LoggerFactory.getLogger(WapPayServiceImpl.class);
	private static final String AUTO_ROUTING = "on"; // 银行自动路由开关
	@Resource(name = "bankOrderService")
	private BankOrderService bankOrderService;
    @Resource(name = "bisExternalPlatformService")
    private BisExternalPlatformService bisExternalPlatformService;
	@Resource(name = "cpsGeneralMainOrderQueryManager")
	private CpsGeneralMainOrderQueryManager mainOrderQuery;
	@Resource(name = "bankOrderManager")
	private BankOrderManager bankOrderManager;
	@Resource(name = "bisBankExtConfigManager")
	BisBankExtConfigManager bisBankExtConfigManager;
	@Resource(name = "bisPayMessageManager")
	BisPayMessageManager bisPayMessageManager;
	@Resource(name = "bisBankSpecialMerchantsManager")
	BisBankSpecialMerchantsManager bisBankSpecialMerchantsManager;
//	@Resource(name = "bisBankSmallMerchantsManager")
//    BisBankSmallMerchantsManager bisBankSmallMerchantsManager;
	@Resource(name = "bisBankProductLimitMerchantsManager")
	BisBankProductLimitMerchantsManager bisBankProductLimitMerchantsManager;
	@Resource(name = "bisConfig")
    private Map<String, String> bisConfig;
	@Resource(name = "bisBankWhiteListMerchantsService")
    private BisBankWhiteListMerchantsService bisBankWhiteListMerchantsService;

	@Override
	public Result pay(BaseMessage base) {
		logger.error("WapPayServiceImpl银行支付处理base对象："+ToStringBuilder.reflectionToString(base));
		Result result = new Result();
		try {
			// 获取订单信息与银行信息
			CpsGenMainOrder mainOrder = getMainOrder(base.getOrderId());
			// 获取SPRING加载的BeanName
			String beanName = "WAP-"+getBeanName(mainOrder, base.getBankIntrChann(),base.getBankBusProd());
//			String beanName = "WAP-CCB-B2C";
			base.setBankOrderId(base.getOrderId());
			WapPayInteractRemoteService bankService = (WapPayInteractRemoteService) SpringContextUtil.getBean(beanName);
			
			//建行wap走大小额商户配置逻辑，只用来判断小额商户
			/*if(BankConstants.BANK_LOGO_CCB.equals(base.getBank())&&BisBankInterfaceChannel._00.value.equals(base.getBankIntrChann().value)){
			    if(bisBankProductLimitMerchantsManager.isExistEnableMerchants(mainOrder.getMainRecvCustId(), base.getBank(), base.getBankBusProd().value, BisMerProductLimit.SMALL.value)){
	                base.setSmallMer(true);
			    }

			}else if (bisBankSmallMerchantsManager.isEnableBankSmallMerchant(mainOrder.getMainRecvCustId(), base.getBank())) {
                base.setSmallMer(true);
            }*/
			if(bisBankProductLimitMerchantsManager.isExistEnableMerchants(mainOrder.getMainRecvCustId(), base.getBank(), base.getBankBusProd().value, BisMerProductLimit.SMALL.value)){
                base.setSmallMer(true);
            }
            
			if(bisBankSpecialMerchantsManager.isEnableBankSpecialMerchant(base.getSpecial2(), base.getBank())){
				base.setSupportCredit(false);
			}
			if(!BisPayCheckUtils.checkExternalOrderID(base.getOrderId())){
			    BaseBisBankExtConfig bankConfig = new BaseBisBankExtConfig();
			    if (isRouteOrWhiteList(base.getSpecial2())) {
                    // 增加银行自动路由开关 add by zhengxue
                    bankConfig = bisBankExtConfigManager.findExtConfigByBankChannelAndBankBusProd(base.getBankBusProd(), base.getBankIntrChann(), base.getBank());
                } else {
                    bankConfig = bisBankExtConfigManager.findExtConfigByBankCodeAndBankBusProd(base.getBankBusProd(), base.getBank());
                }
				
				//设置一级私钥路径
				base.setPrivateKeyPath(bankConfig.getIntrMerPravkeyPath());
				//设置一级私钥密码
				base.setPrivatePwd(bankConfig.getIntrMerPravkeyPwd());
				//设置二级私钥路径
				base.setPrivateKeyPath2nd(bankConfig.getIntrMer2ndPravkeyPath());
				//设置二级私钥密码
				base.setPrivatePwd2nd(bankConfig.getIntrMer2ndPravkeyPwd());
				//设置公钥路径
				base.setPublicKeyPath(bankConfig.getIntrBankPubkeyPath());
				//设置商户号
				base.setMerID(bankConfig.getIntrMernum1());
				//设置二级商户号
				base.setMerID2nd(bankConfig.getIntrMernum2());
				//设置结算账户网点联行号
				base.setBranchCode(bankConfig.getBranchCode());
				//设置银行支付地址
				base.setPayUrl(bankConfig.getPayUrl());
				//设置支付后台通知地址
				base.setPayRuturnUrl(bankConfig.getPayRuturnUrl());
				//设置支付后前通知地址
				base.setPayNotifyUrl(bankConfig.getPayNotifyUrl());
			}
			//绛惧悕
			result = bankService.pay(base);
			base = (BaseMessage)result.getDefaultModel();
			logger.error("WapPayServiceImpl银行支付签名返回处理base对象："+ToStringBuilder.reflectionToString(base));
			// 校验银行订单不能为多条
            List<BankOrder> bankOrders =  bankOrderService.getBankOrdersByGopayOrderId(base.getOrderId());
            if(bankOrders!=null && bankOrders.size()>0){
                result.setResultCode(ProcCodeConstants.PROC_CODE_100E5015);// 已存在相同的订单
                result.setSuccess(false);
                return result;
            }
         // 新增bankOrder info
            base.setBankOrderType(BankOrderType.GOPAY_BIS_ORDER);//订单类型：新平台订单
			bankOrderService.addBankOrder(base);
		} catch (GopayException e) {
			logger.error("WapPayServiceImpl pay error: ", e);
			result.setResultCode(e.getErrCode());
			result.setSuccess(false);
		} catch (Exception e) {
			logger.error("WapPayServiceImpl pay error: ", e);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100F1002);
			result.setSuccess(false);
		}
		return result;
	}

	@Override
	public Result bankBack(BaseMessage base) {
		logger.error("WapPayServiceImpl银行返回处理base对象："+ToStringBuilder.reflectionToString(base));
		Result result = new Result();
		try {
			if (base.getBankOrderId() == null || base.getBankOrderId().equals("")) {
			    BankOrder bankOrder = new BankOrder();
				base.setOutStlmCd(base.getBank());
				BaseBisBankExtConfig bankConfig = new BaseBisBankExtConfig();
				// 银行自动路由修改支付返回无订单号订单,获取产品渠道方法(由获取当前生效渠道改为根据银行、产品、渠道码获取) add by zhengxue
                bankConfig = bisBankExtConfigManager.findExtConfigByBankChannelAndBankBusProd(base.getBankBusProd(), base.getBankIntrChann(), base.getBank());

				if(bankConfig !=null){
			        //设置一级私钥路径
	                base.setPrivateKeyPath(bankConfig.getIntrMerPravkeyPath());
	                //设置一级私钥密码
	                base.setPrivatePwd(bankConfig.getIntrMerPravkeyPwd());
	                //设置二级私钥路径
	                base.setPrivateKeyPath2nd(bankConfig.getIntrMer2ndPravkeyPath());
	                //设置二级私钥密码
	                base.setPrivatePwd2nd(bankConfig.getIntrMer2ndPravkeyPwd());
	                //设置公钥路径
	                base.setPublicKeyPath(bankConfig.getIntrBankPubkeyPath());
				}		
				// 工行Wap特殊处理
				if (StringUtils.equals(BankConstants.BANK_LOGO_ICBC, base.getBank())&& base instanceof IcbcB2cMessage) {
				    String beanName="WAP-ICBC-B2C";
					// 验签
					WapPayInteractRemoteService bankService = (WapPayInteractRemoteService) SpringContextUtil.getBean(beanName);
					result = bankService.bankBack(base);
					base = (BaseMessage) result.get("res");
					logger.error("WapPayServiceImpl工商银行B2C验签返回处理base对象："+ToStringBuilder.reflectionToString(base));
					if(result.isSuccess()&& (Boolean) result.getDefaultModel()){
					    //记录前台通知时间
					    if(base.isFront()){
	                        bankOrderManager.updateFrontBackTime(base.getOrderId());
	                        logger.info("记录前台返回时间：订单号【"+base.getOrderId()+"】记录成功，bis_bank_main_order表更新前台返回时间");
	                        return result;
	                    }
					    if(result.isOrderStatus()){
	                        bankOrder = bankOrderManager.getBankOrderById(base.getBankOrderId());
	                        Map<String, String> param = (Map<String, String>) result.getModel("isNotifyCashier");
	                        String amt = (String) param.get("amt"); // 银行返回交易金额
	                        if (bankOrder.getSendBankAmt() != null
	                                && bankOrder.getSendBankAmt().compareTo(new BigDecimal(amt)) != 0) {
	                            // 银行返回金额与平台上送金额不符
	                            bankOrderManager.updateAmountError(bankOrder.getOrderId());
	                            logger.error("银行【 "+beanName+"】返回处理结果：国付宝订单号【"+base.getOrderId()+"】金额比对异常");
	                            result.setSuccess(false);
	                            result.setResultCode(ProcCodeConstants.PROC_CODE_100E5079);
	                            result.setErrorMsg("通知订单金额不一致");
	                            return result;
	                        }
	                        
	                        bankOrderManager.updateBackSuccess(base.getOrderId());
	                        logger.error("银行【 "+beanName+"】返回处理结果：订单号【"+base.getOrderId()+"】验签成功，bis_bank_main_order表更新成功状态");
	                    }
					}else {
	                    // 验签失败
	                    bankOrderManager.updateBackVerifyFail(base.getOrderId());
	                    logger.error("银行【 "+beanName+"】返回处理结果：订单号【"+base.getOrderId()+"】验签失败，bis_bank_main_order表更新失败状态");
	                }
					base.setOrderId(bankOrder.getOrderId());
					// 是否验签成功过
	                if (StringUtils.equals(bankOrder.getOrderStatus(),BankOrderStatus.BANK_CALL_SUCCESS)) {
	                    result.setDefaultModel(true);
	                    result.setSuccess(true);
	                }
	                return result;
				}
				
				// 验签
                String beanName = getBankBeanName(base); //只返回密文银行获取beanName
                BankInteractRemoteService bankService = (BankInteractRemoteService) SpringContextUtil.getBean(beanName);
                result = bankService.bankBack(base);
                base = (BaseMessage) result.get("res");
                logger.error("WapPayServiceImpl验签返回处理base对象："+ToStringBuilder.reflectionToString(base));
                bankOrder = bankOrderManager.getBankOrderById(base.getBankOrderId());
                base.setOrderId(bankOrder.getOrderId());
                // 是否验签成功过
                if (StringUtils.equals(bankOrder.getOrderStatus(),BankOrderStatus.BANK_CALL_SUCCESS)) {
                    result.setDefaultModel(true);
                    result.setSuccess(true);
                }
                return result;
			}
			BankOrder bankOrder = null;
			bankOrder = bankOrderManager.getBankOrderById(base.getBankOrderId());
			// 自动路由需使用主订单表对象,挪到此处获取 add by zhengxue
            CpsGenMainOrder cpsMainOrder = new CpsGenMainOrder();
			
        	String bankBizProdCode = bankOrder.getBankBizProdCode();
        	base.setOrderId(bankOrder.getOrderId());
        	if(BisBankBusinessProd._00.value.equals(bankBizProdCode)){
        		base.setBankBusProd(BisBankBusinessProd._00);
        	}else if(BisBankBusinessProd._01.value.equals(bankBizProdCode)){
        		base.setBankBusProd(BisBankBusinessProd._01);
			}else if(BisBankBusinessProd._11.value.equals(bankBizProdCode)){
				base.setBankBusProd(BisBankBusinessProd._11);
        	}else{
            	throw new GopayException(ProcCodeConstants.PROC_CODE_100E1141);
            }
        	
        	//如果为外部平台订单
			if(BisPayCheckUtils.checkExternalOrderID(bankOrder.getOrderId())){
				//获取外部订单交易对象
				BisPayMessage bisPayMessage = bisPayMessageManager.getBisPayMessageByGopayOrderId(bankOrder.getOrderId());
				//如果使用外部平台自己的订单
				if(bisPayMessage.getIsThroughBis().equals("1")){
					base.setOutStlmCd(base.getBank());
					BisBankMerchant bisBankMerchant = bisExternalPlatformService.getBankMerchant(bisPayMessage.getPlatformId(), bankOrder.getBankCode(), base.getBankBusProd().value);
					//设置一级私钥路劲
					base.setPrivateKeyPath(bisBankMerchant.getIntrMerPravkeyPath());
					 //设置一级私钥密码
					base.setPrivatePwd(bisBankMerchant.getIntrMerPravkeyPwd());
					//设置二级私钥路径
					base.setPrivateKeyPath2nd(bisBankMerchant.getIntrMer2ndPravkeyPath());
					//设置二级私钥密码
					base.setPrivatePwd2nd(bisBankMerchant.getIntrMer2ndPravkeyPwd());
					//设置公钥路径
					base.setPublicKeyPath(bisBankMerchant.getIntrBankPubkeyPath());
				}else{
					base.setOutStlmCd(base.getBank());
					BaseBisBankExtConfig bankConfig = bisBankExtConfigManager.findExtConfigByBankCodeAndBankBusProd(base.getBankBusProd(), bankOrder.getBankCode());
					//设置一级私钥路径
					base.setPrivateKeyPath(bankConfig.getIntrMerPravkeyPath());
					//设置一级私钥密码
					base.setPrivatePwd(bankConfig.getIntrMerPravkeyPwd());
					//设置二级私钥路径
					base.setPrivateKeyPath2nd(bankConfig.getIntrMer2ndPravkeyPath());
					//设置二级私钥密码
					base.setPrivatePwd2nd(bankConfig.getIntrMer2ndPravkeyPwd());
					//设置公钥路径
					base.setPublicKeyPath(bankConfig.getIntrBankPubkeyPath());
				}
			}else{
			    // 获取订单信息与银行信息
			    cpsMainOrder = getMainOrder(bankOrder.getOrderId());
				base.setOutStlmCd(base.getBank());
				BaseBisBankExtConfig bankConfig = new BaseBisBankExtConfig();
                if (isRouteOrWhiteList(cpsMainOrder.getMerId())) {
                    // 增加银行自动路由开关 add by zhengxue
                    bankConfig = bisBankExtConfigManager.findExtConfigByBankChannelAndBankBusProd(base.getBankBusProd(), BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()), bankOrder.getBankCode());
                } else {
                    bankConfig = bisBankExtConfigManager.findExtConfigByBankCodeAndBankBusProd(base.getBankBusProd(), bankOrder.getBankCode());
                }
				
				//设置一级私钥路径
				base.setPrivateKeyPath(bankConfig.getIntrMerPravkeyPath());
				//设置一级私钥密码
				base.setPrivatePwd(bankConfig.getIntrMerPravkeyPwd());
				//设置二级私钥路径
				base.setPrivateKeyPath2nd(bankConfig.getIntrMer2ndPravkeyPath());
				//设置二级私钥密码
				base.setPrivatePwd2nd(bankConfig.getIntrMer2ndPravkeyPwd());
				//设置公钥路径
				base.setPublicKeyPath(bankConfig.getIntrBankPubkeyPath());
			}
			String beanName = "";
			//如果定单为外部平台
			if(BisPayCheckUtils.checkExternalOrderID(bankOrder.getOrderId())){
				beanName = getExternalBeanName(base,bankOrder);
			}else{
				// 获取订单信息与银行信息
				CpsGenMainOrder mainOrder = getMainOrder(bankOrder.getOrderId());
				// 获取SPRING加载的BeanName
				beanName ="WAP-" + getBeanName(mainOrder,BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()),BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));
			}
			/****************** 处理银行多次通知 begin ***********************/
			// 是否验签成功过
			if (StringUtils.equals(bankOrder.getOrderStatus(),BankOrderStatus.BANK_CALL_SUCCESS) || StringUtils.equals(bankOrder.getOrderStatus(),BankOrderStatus.ENTER_ACCOUNT_FIAL)) {
				WapPayInteractRemoteService bankService = (WapPayInteractRemoteService) SpringContextUtil.getBean(beanName);
				result = bankService.bankBack(base);
				result.setDefaultModel(true);
				result.setSuccess(true);
				return result;
			}
			// 是否验签失败过
			if (StringUtils.equals(bankOrder.getOrderStatus(),BankOrderStatus.VERIFY_FAIL)) {
				result.setDefaultModel(false);
				result.setSuccess(true);
				return result;
			}
			/************** 处理银行多次通知 end *******************/
			// 验签
			WapPayInteractRemoteService bankService = (WapPayInteractRemoteService) SpringContextUtil.getBean(beanName);
			result = bankService.bankBack(base);
			if (base.isFront()) {
			    bankOrderManager.updateFrontBackTime(base.getOrderId());
                logger.info("记录前台返回时间：订单号【"+base.getOrderId()+"】记录成功，bis_bank_main_order表更新前台返回时间");
                return result;
            }
            if(result.isOrderStatus()){
                bankOrder = bankOrderManager.getBankOrderById(base.getBankOrderId());
                Map<String, String> param = (Map<String, String>) result.getModel("isNotifyCashier");
                String amt = (String) param.get("amt"); // 银行返回交易金额
                if (bankOrder.getSendBankAmt() != null
                        && bankOrder.getSendBankAmt().compareTo(new BigDecimal(amt)) != 0) {
                    // 银行返回金额与平台上送金额不符
                    bankOrderManager.updateAmountError(bankOrder.getOrderId());
                    logger.error("银行【 "+beanName+"】返回处理结果：国付宝订单号【"+base.getOrderId()+"】金额比对异常");
                    result.setSuccess(false);
                    result.setResultCode(ProcCodeConstants.PROC_CODE_100E5079);
                    result.setErrorMsg("通知订单金额不一致");
                    return result;
                }
				bankOrderManager.updateBackSuccess(bankOrder.getOrderId());
				logger.error("银行【 "+beanName+"】返回处理结果：国付宝订单号【"+base.getOrderId()+"】验签成功，bis_bank_main_order表更新成功状态");
			} else {
				// 验签失败
				bankOrderManager.updateBackVerifyFail(bankOrder.getOrderId());
				logger.error("银行【 "+beanName+"】返回处理结果：国付宝订单号【"+base.getOrderId()+"】验签失败，bis_bank_main_order表更新失败状态");
			}
		} catch (GopayException e) {
			logger.error("WapPayServiceImpl bankBack error: ", e);
			result.setResultCode(e.getErrCode());
			result.setSuccess(false);
		} catch (Exception e) {
			logger.error("WapPayServiceImpl bankBack error: ", e);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100F1002);
			result.setSuccess(false);
		}
		return result;
	}

	@Override
	public Result query(BaseMessage base) {
		Result result = new Result();
		try {
			base.setSupportCredit(true);
			logger.error("WapPayServiceImpl银行查询处理base对象："+ToStringBuilder.reflectionToString(base));
			CpsGenMainOrder mainOrder = getMainOrder(base.getOrderId());
			// 获取SPRING加载的BeanName
			String outStlmId = getOutStlmId(mainOrder,base.getBankIntrChann(),base.getBankBusProd());
			base.setOutStlmCd(outStlmId);
			base.setAmount(mainOrder.getTotalOrderAmt());
			if (mainOrder.getSettleAmt() != null) {
	            // 发送银行金额取结算金额,若为空则取总金额字段
	            base.setAmount(mainOrder.getSettleAmt());
	        }
			String beanName = getBeanName(mainOrder,base.getBankIntrChann(),base.getBankBusProd());
			WapPayInteractRemoteService bankService = (WapPayInteractRemoteService) SpringContextUtil.getBean(beanName);
			//妫�煡鏄惁涓洪闄╁晢鎴�
            List<BankOrder> bankOrders = bankOrderService.getBankOrdersByGopayOrderId(base.getOrderId());
            String disableCreditCard = ((BankOrder) bankOrders.get(0)).getDisableCreditCard();
            String disableSmallMerchant = ((BankOrder) bankOrders.get(0)).getDisableSmallMerchant();
            if ("1".equals(disableCreditCard)) {
                base.setSupportCredit(false);
            }

            if("1".equals(disableSmallMerchant)){
                base.setSmallMer(true);
            }

			if(!BisPayCheckUtils.checkExternalOrderID(base.getOrderId())){
				// 根据银行业务产品代码、通道代码、银行代码获取通道配置信息
				BaseBisBankExtConfig bankConfig = bisBankExtConfigManager.findExtConfigByBankChannelAndBankBusProd(base.getBankBusProd(), base.getBankIntrChann(), base.getBank());
				//设置一级私钥路径
				base.setPrivateKeyPath(bankConfig.getIntrMerPravkeyPath());
				//设置一级私钥密码
				base.setPrivatePwd(bankConfig.getIntrMerPravkeyPwd());
				//设置二级私钥路径
				base.setPrivateKeyPath2nd(bankConfig.getIntrMer2ndPravkeyPath());
				//设置二级私钥密码
				base.setPrivatePwd2nd(bankConfig.getIntrMer2ndPravkeyPwd());
				//设置公钥路径
				base.setPublicKeyPath(bankConfig.getIntrBankPubkeyPath());
				//设置商户号
				base.setMerID(bankConfig.getIntrMernum1());
				//设置二级商户号
				base.setMerID2nd(bankConfig.getIntrMernum2());
				//设置结算账户网点联行号
				base.setBranchCode(bankConfig.getBranchCode());
				//设置银行查询地址
				base.setQueryUrl(bankConfig.getQueryUrl());
			}
			//查询
			result = bankService.query(base);
			logger.error("WapPayServiceImpl银行查询返回base对象："+ToStringBuilder.reflectionToString(result));
		} catch (GopayException e) {
			logger.error("WapPayServiceImpl query error: ", e);
			result.setResultCode(e.getErrCode());
			result.setSuccess(false);
		} catch (Exception e) {
			logger.error("WapPayServiceImpl query error: ", e);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100F1002);
			result.setSuccess(false);
		}
		return result;
	}

	/**
	 * 北京银行查询返回验签单独处理
	 */
	@Override
	public Result queryBack(BaseMessage base) {
		logger.error("WapPayServiceImpl北京银行查询验签返回处理base对象："+ToStringBuilder.reflectionToString(base));
		Result result = new Result();
		if (base.getBankOrderId() == null || base.getBankOrderId().equals("")) {
			base.setOutStlmCd(base.getBank());
			BaseBisBankExtConfig bankConfig = new BaseBisBankExtConfig();
			// 银行自动路由修改北京银行查询获取产品渠道方法(由获取当前生效渠道改为根据银行、产品、渠道码获取) add by zhengxue
            bankConfig = bisBankExtConfigManager.findExtConfigByBankChannelAndBankBusProd(base.getBankBusProd(), base.getBankIntrChann(), base.getBank());
            
			//设置一级私钥路径
			base.setPrivateKeyPath(bankConfig.getIntrMerPravkeyPath());
			//设置一级私钥密码
			base.setPrivatePwd(bankConfig.getIntrMerPravkeyPwd());
			//设置二级私钥路径
			base.setPrivateKeyPath2nd(bankConfig.getIntrMer2ndPravkeyPath());
			//设置二级私钥密码
			base.setPrivatePwd2nd(bankConfig.getIntrMer2ndPravkeyPwd());
			//设置公钥路径
			base.setPublicKeyPath(bankConfig.getIntrBankPubkeyPath());
			// 验签
			WapPayInteractRemoteService bankService = (WapPayInteractRemoteService) SpringContextUtil.getBean("BOBJ-B2C");
			result = bankService.bankBack(base);
			base = (BaseMessage) result.get("res");
			logger.error("WapPayServiceImpl北京银行B2C查询验签返回处理base对象："+ToStringBuilder.reflectionToString(base));
			if (result.isSuccess()&& (Boolean) result.getDefaultModel()) {
				// 验签成功
				bankOrderManager.updateQueryBackSuccess(base.getOrderId());
				logger.error("北京银行B2C查询验签返回处理结果：订单号【"+base.getOrderId()+"】验签成功，bis_bank_main_order表更新成功状态");
			} else {
				// 验签失败
				bankOrderManager.updateQueryBackVerifyFail(base.getOrderId());
				logger.error("北京银行B2C查询验签返回处理结果：订单号【"+base.getOrderId()+"】验签失败，bis_bank_main_order表更新失败状态");
			}
		}
		return result;


	}

	@Override
	public Result refund(BaseMessage base) {
		return null;
	}

	/**
	 * @author guomuye
	 * 闇�涓�釜filedate
	 */
	@Override
	public Result dayend(BaseMessage base) {
		logger.error("WapPayServiceImpl银行查询处理base对象："+ToStringBuilder.reflectionToString(base));
		Result result = new Result();
		try {
			// 鑾峰彇SPRING鍔犺浇鐨凚eanName
			String beanName = getBeanName(base);
			if(!SpringContextUtil.containsBean(beanName)){
	            logger.error("spring bean does not exist: " + base.getBank()+"-"+base);
	            result.setResultCode(ProcCodeConstants.PROC_CODE_300G1011);
	            result.setErrorMsg(beanName+":spring获得bankServiceImpl调用类失败");
	            return result;
			}
			WapPayInteractRemoteService bankService = (WapPayInteractRemoteService) SpringContextUtil.getBean(beanName);
			result = bankService.dayend(base);
			logger.info("WapPayServiceImpl银行查询返回base对象："+ToStringBuilder.reflectionToString(result));
		} catch (GopayException e) {
			logger.error("WapPayServiceImpl dayend error: ", e);
			result.setResultCode(e.getErrCode());
			result.setSuccess(false);
		} catch (Exception e) {
			logger.error("WapPayServiceImpl dayend error: ", e);
			result.setResultCode(ProcCodeConstants.PROC_CODE_300G1000);
			result.setSuccess(false);
		}
		return result;
	}

	/**
	 * 获取订单信息
	 * @param //String
	 * @return CpsGenMainOrder
	 * @throws com.gopay.common.exception.GopayException
	 */
	private CpsGenMainOrder getMainOrder(String orderId) throws GopayException {
		if (orderId == null || "".equals(orderId)) {
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E5041);
		}
		// 获取主订单表
		CpsGenMainOrder mainOrder = mainOrderQuery.get(orderId);
		if (mainOrder == null) {
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E5041);
		}
		return mainOrder;
	}

	/**
	 * 获取SPRING加载的BeanName
	 * @author guomuye
	 * @throws com.gopay.common.exception.GopayException
	 */
	private String getBeanName(BaseMessage base)throws GopayException {
		int tradeType = base.getTradeType();
		String buffix = TradeType.getTradeType(tradeType);
		String suffix = base.getBank();
		return suffix+"-"+buffix;
	}
	/**
	 * 获取SPRING加载的BeanName
	 *
	 * <pre>
	 * BeanName规范:银行编码-交易类型，如TBANK-B2B
	 * </pre>
	 *
	 * @param mainOrder
	 *            订单信息
	 * @param //bankInfo
	 *            银行信息
	 * @return
	 * @throws com.gopay.common.exception.GopayException
	 */
	private String getBeanName(CpsGenMainOrder mainOrder,BisBankInterfaceChannel inChann, BisBankBusinessProd bankBusProd)throws GopayException {
		String beanSuffix = TradeType.getOrderTrandType(mainOrder.getPayChannel());
		String outStlmId = getOutStlmId(mainOrder,inChann,bankBusProd);
		String beanName = outStlmId + "-" + beanSuffix;
		return beanName;
	}

    /**
     * 获取SPRING加载的BeanName
     * BeanName规范:银行编码-交易类型，如TBANK-B2B
     * @param //mainOrder 璁㈠崟淇℃伅
     * @param //bankInfo 閾惰淇℃伅
     * @return String
     * @throws com.gopay.common.exception.GopayException
     */
    private String getExternalBeanName(BaseMessage message,BankOrder bankOrder) throws GopayException {
        String beanName ="";
        if (bankOrder != null) {
        	String beanSuffix="";
        	String outStlmId="";
        	String chennelCodeValue = BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()).value;
        	String bankBizProdCode = BisBankBusinessProd.get(bankOrder.getBankBizProdCode()).value;
        	if(BisBankBusinessProd._00.value.equals(bankBizProdCode)){
        		beanSuffix = "B2C";
        	}else if(BisBankBusinessProd._01.value.equals(bankBizProdCode)){
        		beanSuffix = "B2B";
			}else if(BisBankBusinessProd._11.value.equals(bankBizProdCode)){
				beanSuffix = "B2C";
        	}else{
            	throw new GopayException(ProcCodeConstants.PROC_CODE_100E1141);
            }
    		if (StringUtils.equals(TradeType.TRADE_TYPE_B2C, beanSuffix)) {
    			outStlmId = InitialSpringBeanName.getOutStlmCd(chennelCodeValue,bankBizProdCode,bankOrder.getBankCode());
    		} else {
    			outStlmId = bankOrder.getBankCode();
    		}
    		message.setBank(outStlmId);
        	beanName = outStlmId+"-"+beanSuffix;
        	return beanName;
        }else{
        	throw new GopayException(ProcCodeConstants.PROC_CODE_100E1141);
        }
    }

    /**
     * @param mainOrder
     * @param inChann
     * @param bankBusProd
     * @return String
     * @throws com.gopay.common.exception.GopayException
     */
	private String getOutStlmId(CpsGenMainOrder mainOrder,BisBankInterfaceChannel inChann, BisBankBusinessProd bankBusProd)throws GopayException {
		String beanSuffix = TradeType.getOrderTrandType(mainOrder.getPayChannel());
		String outStlmId = "";
		if (StringUtils.equals(TradeType.TRADE_TYPE_B2C, beanSuffix)) {
			outStlmId = InitialSpringBeanName.getOutStlmCd(inChann.value,bankBusProd.value, mainOrder.getOutStlmId());
		} else {
			outStlmId = mainOrder.getOutStlmId();
		}
		return outStlmId;
	}
	
	/**
     * 获取SPRING加载的BeanName(银行返回密文)
     * BeanName规范:银行编码-交易类型，如TBANK-B2B
     * @param message 
     * @return String
     * @throws GopayException
     */
    private String getBankBeanName(BaseMessage base) throws GopayException {
        if (StringUtils.equals(BankConstants.BANK_LOGO_ICBC, base.getBank()) && base instanceof IcbcB2cMessage) {
            return "ICBC-B2C";
        } else if (StringUtils.equals(BankConstants.BANK_LOGO_BOCOM, base.getBank()) && base instanceof BocomB2bReq) {
            return "BOCOM-B2B";
        } else if (StringUtils.equals(BankConstants.BANK_LOGO_CMBC, base.getBank()) && base instanceof CmbcB2cMessage) {
            return "CMBC-B2C";
        } else if (StringUtils.equals(BankConstants.BANK_LOGO_CMBC, base.getBank()) && base instanceof CmbcB2bMessage) {
            return "CMBC-B2B";
        } else if (StringUtils.equals(BankConstants.BANK_LOGO_BOBJ, base.getBank()) && base instanceof BobjB2cMessage) {
            return "BOBJ-B2C";
        } else if (StringUtils.equals(BankConstants.BANK_LOGO_CITIC, base.getBank()) && base instanceof CiticB2cMessage) {
            return "CITIC-B2C";
        } else if (StringUtils.equals(BankConstants.BANK_LOGO_CITIC, base.getBank()) && base instanceof CiticB2bMessage) {
            return "CITIC-B2B";
        } else if (StringUtils.equals(BankConstants.BANK_LOGO_ABC, base.getBank()) && base instanceof AbcB2cMessage) {
            return "ABC-B2C";
        } else if (StringUtils.equals(BankConstants.BANK_LOGO_ABC, base.getBank()) && base instanceof AbcB2bMessage) {
            return "ABC-B2B";
        } else if (StringUtils.equals(BankConstants.BANK_LOGO_HXBC, base.getBank()) && base instanceof HXEB2CReqPay) {
            return "HXBC-B2C";
        } else if (StringUtils.equals(BankConstants.BANK_LOGO_YSPAY, base.getBank()) && base instanceof YspayMessage) {
            return "YSPAY-B2C";
        } else {
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E7022);
        }
    }
    
    /**
     * 是否为自动路由
     * 
     * @param merId
     * @return
     */
    private boolean isRouteOrWhiteList(String merId) {
        // 是否为白名单商户
        boolean isWhite = bisBankWhiteListMerchantsService.isWhiteListMerchant(merId);
        if (AUTO_ROUTING.equals(bisConfig.get("GOPAY.AUTO.ROUTING")) || isWhite) {
            return true;
        } else {
            return false;
        }
    }
}